﻿using System;
using System.IO;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Drawing.Drawing2D;

namespace MakeThumbnail
{
    public partial class Frm_Main : Form
    {
        private bool aIsSavaPath_Def = true;

        public Frm_Main()
        {
            InitializeComponent();
        }

        private void btn_Make_Click(object sender, EventArgs e)
        {
            string iFilePath_Y, iFilePath_Sava;
            iFilePath_Y = this.txt_FilePath_Y.Text;
            if (rbtn_FilePath_Def.Checked)
            {
                iFilePath_Sava = iFilePath_Y;
            }
            else
            {
                iFilePath_Sava = this.txt_FilePath_Sava.Text;
            }
            if ((iFilePath_Sava.Substring(iFilePath_Sava.Length - 1, 1)) != "//")
            {
                iFilePath_Sava = iFilePath_Sava + "//";
            }
            if (Directory.Exists(iFilePath_Y) == false)
            {
                MessageBox.Show("无效的源路径！");
                return; 
            }
            if (Directory.Exists(iFilePath_Sava) == false)
            {
                Directory.CreateDirectory(iFilePath_Sava);
            }

            string[] iFiles = Directory.GetFiles(iFilePath_Y);
            int iFileNum = iFiles.Length;
            int iFile_NotImg = 0, iFile_OK = 0, iFile_Fail = 0;
            foreach (string iFile in iFiles)
            {
                if (CheckTrueFileName(iFile)==false)
                {
                    iFile_NotImg++;
                    continue;
                }

                Brush iBackColo = new SolidBrush(Color.White);
                try
                {
                    using (Image iImgForFile = Image.FromFile(iFile))
                    {
                        using (Image iImg_T = CreateThumbnail(iImgForFile, 85, 85, iBackColo))
                        {
                            if (iImg_T == null)
                            {
                                continue;
                            }

                            string iFilename_Y = Path.GetFileName(iFile);
                            string iFilename = iFilename_Y.Replace("m", "s");
                            if (iFilename == iFilename_Y)
                            {
                                iFilename = "s_" + iFilename_Y;
                            }
                            iImg_T.Save(iFilePath_Sava + iFilename);
                            iFile_OK++;
                        }
                    }
                }
                catch
                {
                    iFile_Fail++;
                }
            }

            MessageBox.Show("转换完毕！" + Environment.NewLine
                + string.Format("成功生成：{0}个；失败：{2}个；非图片文件：{1}个"
                , iFile_OK, iFile_Fail, iFile_NotImg));
        }

        public static Image CreateThumbnail(Image originalBmp, int desiredWidth, int desiredHeight, Brush backgroundColor)
        {
            //if (originalBmp.Width <= desiredWidth && originalBmp.Height <= desiredHeight)  
            if (originalBmp.Width == desiredWidth && originalBmp.Height == desiredHeight)
            {
                return originalBmp;
            }

            int newWidth, newHeight;
            if (originalBmp.Width > desiredWidth || originalBmp.Height > desiredHeight)
            {
                // scale down the smaller dimension  
                if (desiredWidth * originalBmp.Height < desiredHeight * originalBmp.Width)
                {
                    newWidth = desiredWidth;
                    newHeight = (int)Math.Round((decimal)originalBmp.Height * desiredWidth / originalBmp.Width);
                }
                else
                {
                    newHeight = desiredHeight;
                    newWidth = (int)Math.Round((decimal)originalBmp.Width * desiredHeight / originalBmp.Height);
                }
            }
            else
            {
                newWidth = originalBmp.Width;
                newHeight = originalBmp.Height;
            }

            var newX = (int)Math.Round((desiredWidth - newWidth) / 2.0);
            var newY = (int)Math.Round((desiredHeight - newHeight) / 2.0);

            var bmpOut = new Bitmap(desiredWidth, desiredHeight);

            using (var graphics = Graphics.FromImage(bmpOut))
            {
                graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
                graphics.FillRectangle(backgroundColor, 0, 0, desiredWidth, desiredHeight);
                //graphics.FillRectangle(Brushes.White, 0, 0, newWidth, newHeight);  
                graphics.DrawImage(originalBmp, newX, newY, newWidth, newHeight);
            }

            return bmpOut;
        }

        public bool CheckTrueFileName(string FilePath)
        {
            string path = FilePath;
            System.IO.FileStream fs = new System.IO.FileStream(path, FileMode.Open, FileAccess.Read);
            System.IO.BinaryReader r = new System.IO.BinaryReader(fs);
            string bx = " ";
            byte buffer;
            try
            {
                buffer = r.ReadByte();
                bx = buffer.ToString();
                buffer = r.ReadByte();
                bx += buffer.ToString();
            }
            catch (Exception exc)
            {
            }
            r.Close();
            fs.Close();
            //255216是jpg;7173是gif;6677是BMP,13780是PNG;7790是exe,8297是rar 
            if ((bx == "255216") || (bx == "7173") || (bx == "6677") || (bx == "13780"))
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        private void btn_Path1_Click(object sender, EventArgs e)
        {
            if (this.folderBrowserDialog1.ShowDialog() != DialogResult.OK)
            {
                return;
            }

            txt_FilePath_Y.Text = this.folderBrowserDialog1.SelectedPath;
        }

        private void btn_Path2_Click(object sender, EventArgs e)
        {
            if (this.folderBrowserDialog1.ShowDialog() != DialogResult.OK)
            {
                return;
            }

            txt_FilePath_Sava.Text = this.folderBrowserDialog1.SelectedPath;
        }

        private void rbtn_FilePath_Def_CheckedChanged(object sender, EventArgs e)
        {
            this.txt_FilePath_Sava.Enabled = this.btn_Path2.Enabled = !this.rbtn_FilePath_Def.Checked;
        }

        private void btn_chfilename_Click(object sender, EventArgs e)
        {
            string iFilePath_Y, iFilePath_Sava;
            iFilePath_Y = this.txt_FilePath_Y.Text;
            if (rbtn_FilePath_Def.Checked)
            {
                iFilePath_Sava = iFilePath_Y;
            }
            else
            {
                iFilePath_Sava = this.txt_FilePath_Sava.Text;
            }
            if ((iFilePath_Sava.Substring(iFilePath_Sava.Length - 1, 1)) != "//")
            {
                iFilePath_Sava = iFilePath_Sava + "//";
            }
            if (Directory.Exists(iFilePath_Y) == false)
            {
                MessageBox.Show("无效的源路径！");
                return;
            }
            if (Directory.Exists(iFilePath_Sava) == false)
            {
                Directory.CreateDirectory(iFilePath_Sava);
            }

            string[] iFiles = Directory.GetFiles(iFilePath_Y);
            int iFileNum = iFiles.Length;
            int iFile_NotImg = 0, iFile_OK = 0, iFile_Fail = 0;
            foreach (string iFile in iFiles)
            {
                string iFileName = Path.GetFileName(iFile);
                if (iFileName.IndexOf("m_") == -1)
                {
                    string iNewFilePath = Path.GetDirectoryName(iFile) + "//m_" + iFileName;
                    File.Move(iFile, iNewFilePath);
                    iFile_OK++;
                }
            }

            MessageBox.Show("修改完毕！" + Environment.NewLine
                + string.Format("成功修改：{0}个。", iFile_OK));
        }
    }
}
